﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace NuMvvm.Validation
{
    public class RegularExpressionAttribute : ValidationAttribute
    {
        public RegularExpressionAttribute(string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                throw new ArgumentException("regularExpression");
            }
            Pattern = pattern;
        }

        public string Pattern { get; private set; }

        public bool IgnoreCase { get; set; }

        public bool AllowNullOrEmpty { get; set; }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult result = null;
            if (string.IsNullOrEmpty(value as string) && AllowNullOrEmpty)
            {
                result = null;
            }
            else
            {
                var valueString = value.ToString();
                if (!Regex.IsMatch(valueString, Pattern, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None))
                {
                    result = new ValidationResult(ErrorMessage, validationContext.MemberName);
                }
            }
            return result;
        }
    }
}
